/*
 * @Author: xiaosihan 
 * @Date: 2022-07-11 07:51:56 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2025-10-18 15:49:37
 */
import React, { useEffect, useState } from 'react';
import clsx from 'clsx';
import styles from './index.module.less';
import testApi from '@/api/testApi';
import renderApi from '@/api/renderApi';
import utilsApi from '@/api/utilsApi';
import homeRenderer from "./homeRender";
import homeStore from './HomeStore';
import { observer } from 'mobx-react-lite';
import { toJS } from 'mobx';

import utilsService from '@/srcService/services/utilsService';
utilsService.get_ping();

interface Iprops {
    children?: React.ReactNode;
}

const Home = observer((props: Iprops) => {
    const { loading, error } = homeStore;
    const [renderedImage, setRenderedImage] = useState<string>('');
    const [isRendering, setIsRendering] = useState<boolean>(false);

    useEffect(() => {
        homeStore.initializeData();
        testApi.ping();
    }, []);

    const handleServerRender = async () => {
        setIsRendering(true);
        try {
            const sceneInfo = {
                cameraPosition: homeRenderer.getCamera().position.toArray(),
                cameraRotation: homeRenderer.getCamera().rotation.toArray(),
                sceneId: 'home_scene'
            };

            const response = await renderApi.serverRender(sceneInfo);

            if (response) {
                if (response.data) {
                    setRenderedImage(response.data);
                }
            } else {
                console.error('渲染失败:', response.message || response.data?.message);
                alert(`渲染失败: ${response.message || response.data?.message || '未知错误'}`);
            }
        } catch (error) {
            console.error('服务端渲染失败:', error);
            alert('服务端渲染请求失败，请检查服务端日志');
        } finally {
            setIsRendering(false);
        }
    };

    return (
        <div className={styles.renderControls}>
            <button
                onClick={handleServerRender}
                disabled={isRendering}
                className={styles.renderButton}
            >
                {isRendering ? '渲染中...' : '服务端渲染'}
            </button>
            <div className={styles.contentWrapper}>
                <div ref={dom => homeRenderer.setContainer(dom)} className={styles.container}></div>
                {renderedImage && (
                    <div className={styles.renderedImageContainer}>
                        <img src={renderedImage} alt="服务端渲染结果" className={styles.renderedImage} />
                    </div>
                )}
            </div>
        </div>
    );
});

export default Home;